﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Command.Department;
using SmartCity.BasicData.Api.DTOs;
using SmartCity.BasicData.Domain.Entities;
using SmartCity.BasicData.ErrorCoce;
using SmartCity.BasicData.Infrastructure.Interface;

namespace SmartCity.BasicData.Api.Application.Handler.Department
{
    public class GetDepartmentHandler : IRequestHandler<GetDepartmentCommand, ApiResult<List<DepartmentDto>>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentHandler(IBaseRepository<DepartmentModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }

        public async Task<ApiResult<List<DepartmentDto>>> Handle(GetDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartmentDto>> res = new ApiResult<List<DepartmentDto>>();
            res.Msg = "使用递归查询更方便!";
            res.Code = ApiEnum.Success;
            res.Data = GetDepartmentTree(request.ParentId);//递归方法

            return res;

        }

        /// <summary>
        /// 递归查询部门树
        /// </summary>
        /// <param name="parentId">父Id</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<DepartmentDto> GetDepartmentTree(long? parentId)
        {
            //通过父id可以查找所有未被逻辑删除的子部门集合
            var departments = departRepo.GetAll().Where(x => x.ParentId == parentId&&x.IsDeleted==false).ToList();
            var dtos = mapper.Map<List<DepartmentDto>>(departments);
            foreach (var d in dtos) {
                d.Children = GetDepartmentTree(d.Id);
            }
             return dtos;
        }
    }
}
